package test.file;

import test.file.utils.FileUtils;
import test.file.utils.MergeFile;
import utils.JsonUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class m3u8ToMp4 {

    private static int num, success, fail;
    private static List<String> failList = new ArrayList<>();

    public static void main(String[] args) {
//        String dirPath = "H:\\Android\\data\\com.UCMobile\\files\\UCDownloads\\VideoData";
        String dirPath = "E:\\迅雷下载\\新建文件夹 (2)";
        String targetPath = "E:\\迅雷下载\\新建文件夹 (2)";
        convert(dirPath, targetPath);

        //测试字符串截取
//      String content = "/storage/E5D3-3687/Android/data/com.UCMobile/files/UCDownloads/VideoData/1558545483773/0";
//      System.out.println(subStringToDirName(content));

//        String content = "/satertipjer/342";
//        if(content.indexOf("/") == 0){
//            System.out.println(content.substring(1, content.length()));
//        }
    }

    /**
     * 转换该文件夹下所有文件
     * @param dirPath
     */
    private static void convert(String dirPath, String targetPath) {
        //获取该文件夹下的所有文件的列表
        List<File> fileList = getAllFile(dirPath);
        System.out.println("共需转换文件" + fileList.size() + "个");
        for (File file : fileList) {
            try {
                //读取文件，获取文件内对应文件夹的名称
                List<String> fileContent = FileUtils.readFile1(file);
                //获取文件名
                String dirName = subStringToDirName(fileContent);
                //将文件夹内各文件合并为一个，并用该文件名命名
                concertM3u8ToMp4(dirPath, targetPath, dirName, file.getName());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("-----------------------------------");
        System.out.println("文件总数：" + fileList.size() + "个；成功：" + success + "个；失败：" + fail + "个；");
        System.out.println("失败原因：" + JsonUtil.bean2Str(failList));
    }

    /**
     * 获取该路径下的所有文件
     * @param dirPath
     * @return
     */
    private static List<File> getAllFile(String dirPath) {
        File dirPathFile = new File(dirPath);
        List<File> fileList = new ArrayList<File>();
        if (dirPathFile.exists()) {
            File[] files = dirPathFile.listFiles();
            for (File file : files) {
                if (!file.isDirectory()) {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }

    private static String subStringToDirName(List<String> fileContent) {
        String head = "/storage/E5D3-3687/Android/data/com.UCMobile/files/UCDownloads/VideoData/";
        String result = "";
        for (String content : fileContent) {
            try {
                result = content.substring(head.length(), content.lastIndexOf("/"));
                //亚色世界VideoData后有两个斜线
                if(result.indexOf("/") == 0){
                    result = result.substring(1);
                }
            } catch (Exception e) {

            }
            if (result.length() > 0) {
                break;
            }
        }
        return result;
    }

    /**
     * 合并文件
     *
     * @param dirPath 文件夹路径
     * @param targetPath 目的路径
     * @param dirName 文件夹名称
     * @param fileName 合并后的文件名称
     */
    private static void concertM3u8ToMp4(String dirPath, String targetPath, String dirName, String fileName) throws Exception {
        try {
            System.out.println("-----------------------------------");
            System.out.println(++num + "、开始操作文件夹：" + dirPath + " , " + dirName + " , " + fileName);
            String m3u8FilePath = dirPath + File.separator + dirName;
            File m3u8Dir = new File(m3u8FilePath);
            if (m3u8Dir.exists()) {
                //删除无关文件
                File tempFile1 = new File(m3u8FilePath + File.separator + ".index.m3u8");
                if (tempFile1.exists()) {
                    tempFile1.delete();
                }
                //删除无关文件
                File tempFile2 = new File(m3u8FilePath + File.separator + ".local.index.m3u8");
                if (tempFile2.exists()) {
                    tempFile2.delete();
                }
                //获取该文件夹下所有文件
                List<File> fileList = getAllFile(m3u8FilePath);
                String[] filePathArr = new String[fileList.size()];
//                String[] filePathArr = new String[10000];
                //将该文件夹下所有文件路径加入数组
                for (File file : fileList) {
                    String filePath = file.getPath();
                    //亚色世界文件夹中以Y2hlbmppbmdjb25n开始
                    String tempNum = filePath.substring(filePath.lastIndexOf(File.separator) + 1).replace("Y2hlbmppbmdjb25n", "");
                    int temp = Integer.parseInt(tempNum);
                    filePathArr[temp] = filePath;
                }
                System.out.println("待合并数组为：" + JsonUtil.bean2Str(filePathArr));
                //拼接文件名
                fileName = targetPath + File.separator + fileName;
                fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".mp4";
                //System.out.println(fileName);
                //合并文件
                boolean mergeResult = MergeFile.mergeFilesForIo(filePathArr, fileName, false);
                if (mergeResult) {
                    success++;
                    System.out.println("合并成功：" + targetPath + " , " + dirName + " , " + fileName);
                } else {
                    String tempStr = "ERROR: 合并失败：" + targetPath + " , " + dirName + " , " + fileName;
                    fail++;
                    failList.add(tempStr);
                    System.err.println(tempStr);
                }
            } else {
                String tempStr = "ERROR: 文件夹不存在：" + m3u8FilePath + "," + fileName;
                fail++;
                failList.add(tempStr);
                System.err.println(tempStr);
            }
        } catch(Exception e){
            fail++;
            failList.add(e.getMessage());
            throw new Exception(e);
        }
    }

    private static String[] strArrSort(String[] strArr) {
        String[] resultArr = new String[strArr.length];
        for (String str : strArr) {
            int temp = Integer.parseInt(str.substring(str.lastIndexOf("\\") + 1));
            resultArr[temp] = str;
        }
        return resultArr;
    }

}

